package com.erli.exchange.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

	public static final int HTTPCLIENT_CONNECT_TIMEOUT = 5;
	public static final int HTTPCLIENT_READ_TIMEOUT = 10;

	public static String httpPost(String url, String params) throws IOException {
		return httpPost(url, params, false);
	}

	public static String httpPost(String url, String params, boolean logResult) throws IOException {
		long start = System.currentTimeMillis();
		String result = null;
		PrintWriter printWriter = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL urlObj = new URL(url);
			httpURLConnection = (HttpURLConnection) urlObj.openConnection();
			httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) "
					+ "AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16");
			httpURLConnection.setConnectTimeout(HTTPCLIENT_CONNECT_TIMEOUT * 1000);
			httpURLConnection.setReadTimeout(HTTPCLIENT_READ_TIMEOUT * 1000);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);

			printWriter = new PrintWriter(new OutputStreamWriter(httpURLConnection.getOutputStream()));
			printWriter.print(params);
			printWriter.flush();
			bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			StringBuilder stringBuilder = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				stringBuilder.append(line);
			}
			result = stringBuilder.toString();
			return result;
		} catch (IOException e) {
			LOGGER.error("http post 出现异常", e);
			throw e;
		} finally {
			if (printWriter != null) {
				try {
					printWriter.close();
				} catch (Exception e) {
					LOGGER.error("关闭输出流出错", e);
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					LOGGER.error("关闭输出流出错", e);
				}
			}
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}

			if (logResult) {
				LOGGER.info("http post (time:{}ms)({}) param({}), result({})", (System.currentTimeMillis() - start),
						url, params, result);
			} else {
				LOGGER.info("http post (time:{}ms)({}) param({}), result.length:({})",
						(System.currentTimeMillis() - start), url, params, result == null ? 0 : result.length());
			}
		}
	}
}
